import { ref } from 'vue';
import api from '../api/api';

// 获取文章列表（新增方法）
export const useArticleList = () => {
  const articles = ref([]);
  const total = ref(0);
  const page = ref(1);
  const limit = ref(10);
  const totalPages = ref(0);
  const loading = ref(false);
  const error = ref('');

  // 获取文章列表
  const fetchArticleList = async (params = {}) => {
    loading.value = true;
    error.value = '';
    page.value = params.page || 1;
    limit.value = params.limit || 10;
    
    try {
      const response = await api.get('/articles', {
        params: {
          page: page.value,
          pageSize: limit.value
        }
      });

      if (response.data.code === 1 && response.data.msg === 'success') {
        articles.value = response.data.data.rows;
        total.value = response.data.data.total;
        totalPages.value = response.data.data.totalPages;
        return {
          articles: articles.value,
          total: total.value,
          totalPages: totalPages.value
        };
      } else {
        error.value = '获取文章失败';
        return null;
      }
    } catch (err) {
      console.error('请求出错:', err);
      error.value = '网络错误，请重试';
      return null;
    } finally {
      loading.value = false;
    }
  };

  return { 
    articles, 
    total, 
    page, 
    limit, 
    loading, 
    error, 
    fetchArticleList 
  };
};